﻿namespace Trove.Web
{
    using System;
    using System.Diagnostics;
    using System.Diagnostics.CodeAnalysis;
    using System.IO;

    using Cavity;

    [Comment("http://stephenwalther.com/blog/archive/2011/12/22/asp-net-mvc-selenium-iisexpress.aspx")]
    public sealed class IisExpress : DisposableObject
    {
        private Process _process;
        
        [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "This is for testing purposes.")]
        public IisExpress(DirectoryInfo directory, int port)
        {
            if (null == directory)
            {
                throw new ArgumentNullException("directory");
            }

            _process = new Process
            {
                StartInfo =
                {
                    FileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), @"IIS Express\iisexpress.exe"),
                    Arguments = "/path:\"{0}\" /port:{1}".FormatWith(directory.FullName, port)
                }
            };

            _process.Start();
        }

        protected override void OnDispose()
        {
            if (null == _process)
            {
                return;
            }

            if (_process.HasExited == false)
            {
                _process.Kill();
            }

            _process = null;
        }
    }
}